//
//  LiveRoomViewControllerAudienceViewController.m
//  CYWFrame
//
//  Created by oldfish on 2018/8/9.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "LiveRoomViewControllerAudience.h"
#import "VideoSession.h"
#import "VideoViewLayouter.h"
#import "KeyCenter.h"

//原腾讯IM部分
#import "TXRTMPSDK/TXLivePlayListener.h"
#import "TXRTMPSDK/TXLivePlayConfig.h"
#import <mach/mach.h>
#import "TCMsgHandler.h"
#import "TCMsgModel.h"
#import "TCPlayerModel.h"
#import "TCConstants.h"
#import <Accelerate/Accelerate.h>
//#import "UMSocialUIManager.h"
//#import <UMSocialCore/UMSocialCore.h>
#import "TCLoginModel.h"
#import "NSString+Common.h"
#import "TCVideoPublishController.h"
#import "AlertShareView.h"

// 礼物展示
#import "PresentView.h"
#import "PresentModel.h"
#import "CustonCell.h"
#import "ADViewCell.h"

// 豪华礼物展示
#import "redCar.h"
#import "planView.h"
#import "flowerAction.h"
#import "shipAction.h"

#import "WKWebViewController.h"
#import "AlertShareView.h"


@interface LiveRoomViewControllerAudience ()<AgoraRtcEngineDelegate,UITextFieldDelegate, TXLivePlayListener,TCPlayDecorateDelegate, TCPlayUGCDecorateViewDelegate, TXVideoRecordListener, ITCLivePushListener, ITCLivePlayListener, PresentViewDelegate, UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource, ADViewCellDelegate>
@property (weak, nonatomic) IBOutlet UILabel *roomNameLabel;
@property (weak, nonatomic) IBOutlet UIView *remoteContainerView;
@property (weak, nonatomic) IBOutlet UIButton *broadcastButton;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *sessionButtons;
@property (weak, nonatomic) IBOutlet UIButton *audioMuteButton;
@property (weak, nonatomic) IBOutlet UIButton *enhancerButton;

@property (strong, nonatomic) AgoraRtcEngineKit *rtcEngine;
@property (assign, nonatomic) BOOL isBroadcaster;
@property (assign, nonatomic) BOOL isMuted;
@property (assign, nonatomic) BOOL shouldEnhancer;
@property (strong, nonatomic) NSMutableArray<VideoSession *> *videoSessions;
@property (strong, nonatomic) VideoSession *fullSession;
@property (strong, nonatomic) VideoViewLayouter *viewLayouter;

@end

@implementation LiveRoomViewControllerAudience
{
    TXLivePlayer *       _txLivePlayer;
    TXLivePlayConfig*    _config;
    TX_Enum_PlayType     _playType;
    TCPlayUGCDecorateView  *_videoRecordView;
    videoIsReadyBlock     _videoIsReady;
    TCLiveInfo           *_liveInfo;
    long long            _trackingTouchTS;
    BOOL                 _startSeek;
    BOOL                 _videoPause;
    BOOL                 _videoFinished;
    BOOL                 _appIsInterrupt;
    float                _sliderValue;
    BOOL                 _isLivePlay;
    BOOL                 _isInVC;
    NSString             *_logMsg;
    NSString             *_rtmpUrl;
    
    NSString             *_biaoUrl;
    NSString             *_gaoUrl;
    
    UIView               *_videoParentView;
    
    AVIMMsgHandler       *_msgHandler;
    BOOL                 _isNotifiedEnterGroup;
    BOOL                  _rotate;
    BOOL                 _isErrorAlert; //是否已经弹出了错误提示框，用于保证在同时收到多个错误通知时，只弹一个错误提示框
    
    BOOL                _isResetVideoRecord;
	
	redCar                  *_car;  // 豪华礼物
	planView                *_plan;
	flowerAction            *_flow;
	shipAction              *_ship;
	
	PresentView             *_presentView; // 礼物展示
	NSMutableArray *expensiveGiftCount;//记录豪华礼物数量
	NSTimer *expensiveGiftTime;//豪华礼物定时器
	
	UITableView *adView;
	ADViewCell *currentCell;
	NSMutableArray *adInfoArr;
	NSMutableArray *adInfoInQueueArr;
	NSInteger endAnimate;
}

static int haohuaCount = 0;//判断上次豪华礼物

- (BOOL)isBroadcaster {
	return self.clientRole == AgoraClientRoleBroadcaster;
}

- (VideoViewLayouter *)viewLayouter {
	if (!_viewLayouter) {
		_viewLayouter = [[VideoViewLayouter alloc] init];
	}
	return _viewLayouter;
}

- (void)setClientRole:(AgoraClientRole)clientRole {
	_clientRole = clientRole;
	
	if (self.isBroadcaster) {
		self.shouldEnhancer = YES;
	}
	[self updateButtonsVisiablity];
}

- (void)setIsMuted:(BOOL)isMuted {
	_isMuted = isMuted;
	[self.rtcEngine muteLocalAudioStream:isMuted];
	[self.audioMuteButton setImage:[UIImage imageNamed:(isMuted ? @"btn_mute_cancel" : @"btn_mute")] forState:UIControlStateNormal];
}

- (void)setVideoSessions:(NSMutableArray<VideoSession *> *)videoSessions {
	_videoSessions = videoSessions;
	if (self.remoteContainerView) {
		[self updateInterfaceWithAnimation:YES];
	}
}

- (void)setFullSession:(VideoSession *)fullSession {
	_fullSession = fullSession;
	if (self.remoteContainerView) {
		[self updateInterfaceWithAnimation:YES];
	}
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self.navigationController setNavigationBarHidden:YES animated:animated];
	self.navigationController.interactivePopGestureRecognizer.delegate = self;
	self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
	self.navigationController.interactivePopGestureRecognizer.enabled = YES;
	[self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
	[super viewDidLoad];
	self.videoSessions = [[NSMutableArray alloc] init];
	
	//self.roomNameLabel.text = self.channelId;
	[self updateButtonsVisiablity];
    [self loadAgoraKit];
    [self initTencentParam];
    [self joinGroup];
    [self initLogicView];
    [self getMallInfo];
}

- (IBAction)doSwitchCameraPressed:(UIButton *)sender {
	[self.rtcEngine switchCamera];
}

- (IBAction)doMutePressed:(UIButton *)sender {
	self.isMuted = !self.isMuted;
}

- (IBAction)doBroadcastPressed:(UIButton *)sender {
	if (self.isBroadcaster) {
		self.clientRole = AgoraClientRoleAudience;
		if (self.fullSession.uid == 0) {
			self.fullSession = nil;
		}
	} else {
		self.clientRole = AgoraClientRoleBroadcaster;
	}
	
	[self.rtcEngine setClientRole:self.clientRole];
	[self updateInterfaceWithAnimation:YES];
}

- (IBAction)doDoubleTapped:(UITapGestureRecognizer *)sender {
	if (!self.fullSession) {
		VideoSession *tappedSession = [self.viewLayouter responseSessionOfGesture:sender inSessions:self.videoSessions inContainerView:self.remoteContainerView];
		if (tappedSession) {
			self.fullSession = tappedSession;
		}
	} else {
		self.fullSession = nil;
	}
}
//腾讯的退出
-(void)closeVC:(BOOL)popViewController{
    [self leaveChannel];
    [self closeVCWithRefresh:NO popViewController:popViewController];
    //    [UMSocialUIManager dismissShareMenuView];
}

- (IBAction)doLeavePressed:(UIButton *)sender {
	[self leaveChannel];
}

- (void)updateButtonsVisiablity {
	[self.broadcastButton setImage:[UIImage imageNamed:self.isBroadcaster ? @"btn_join_cancel" : @"btn_join"] forState:UIControlStateNormal];
	for (UIButton *button in self.sessionButtons) {
		button.hidden = !self.isBroadcaster;
	}
}

- (void)leaveChannel {
	[self setIdleTimerActive:YES];
	
	[self.rtcEngine setupLocalVideo:nil];
	[self.rtcEngine leaveChannel:nil];
	if (self.isBroadcaster) {
		[self.rtcEngine stopPreview];
	}
	
	for (VideoSession *session in self.videoSessions) {
		[session.hostingView removeFromSuperview];
	}
	[self.videoSessions removeAllObjects];
	
    
	if ([self.delegate respondsToSelector:@selector(liveVCNeedClose:)]) {
		[self.delegate liveVCNeedClose:self];
	}
    
}

- (void)setIdleTimerActive:(BOOL)active {
	[UIApplication sharedApplication].idleTimerDisabled = !active;
}

- (void)alertString:(NSString *)string {
	if (!string.length) {
		return;
	}
	
	UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:string preferredStyle:UIAlertControllerStyleAlert];
	[alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:nil]];
	[self presentViewController:alert animated:YES completion:nil];
}

- (void)updateInterfaceWithAnimation:(BOOL)animation {
	if (animation) {
		[UIView animateWithDuration:0.3 animations:^{
			[self updateInterface];
			[self.view layoutIfNeeded];
		}];
	} else {
		[self updateInterface];
	}
}

- (void)updateInterface {
	NSArray *displaySessions;
	if (!self.isBroadcaster && self.videoSessions.count) {
		displaySessions = [self.videoSessions subarrayWithRange:NSMakeRange(1, self.videoSessions.count - 1)];
	} else {
		displaySessions = [self.videoSessions copy];
	}
	
	[self.viewLayouter layoutSessions:displaySessions fullSession:self.fullSession inContainer:self.remoteContainerView];
	[self setStreamTypeForSessions:displaySessions fullSession:self.fullSession];
}

- (void)setStreamTypeForSessions:(NSArray<VideoSession *> *)sessions fullSession:(VideoSession *)fullSession {
	if (fullSession) {
		for (VideoSession *session in sessions) {
			[self.rtcEngine setRemoteVideoStream:session.uid type:(session == self.fullSession ? AgoraVideoStreamTypeHigh : AgoraVideoStreamTypeLow)];
		}
	} else {
		for (VideoSession *session in sessions) {
			[self.rtcEngine setRemoteVideoStream:session.uid type:AgoraVideoStreamTypeHigh];
		}
	}
}

- (void)addLocalSession {
	VideoSession *localSession = [VideoSession localSession];
	[self.videoSessions addObject:localSession];
	[self.rtcEngine setupLocalVideo:localSession.canvas];
	[self updateInterfaceWithAnimation:YES];
}

- (VideoSession *)fetchSessionOfUid:(NSUInteger)uid {
	for (VideoSession *session in self.videoSessions) {
		if (session.uid == uid) {
			return session;
		}
	}
	return nil;
}

- (VideoSession *)videoSessionOfUid:(NSUInteger)uid {
	VideoSession *fetchedSession = [self fetchSessionOfUid:uid];
	if (fetchedSession) {
		return fetchedSession;
	} else {
		VideoSession *newSession = [[VideoSession alloc] initWithUid:uid];
		[self.videoSessions addObject:newSession];
		[self updateInterfaceWithAnimation:YES];
		return newSession;
	}
}

//MARK: - Agora Media SDK
- (void)loadAgoraKit {
	self.rtcEngine = [AgoraRtcEngineKit sharedEngineWithAppId:[KeyCenter AppId] delegate:self];
	[self.rtcEngine setChannelProfile:AgoraChannelProfileLiveBroadcasting];
	[self.rtcEngine enableDualStreamMode:YES];
	[self.rtcEngine enableVideo];
	[self.rtcEngine setVideoProfile:self.videoProfile swapWidthAndHeight:YES];
	[self.rtcEngine setClientRole:self.clientRole];
	
	if (self.isBroadcaster) {
		[self.rtcEngine startPreview];
	}
	
	[self addLocalSession];
	
	int code = [self.rtcEngine joinChannelByToken:nil channelId:self.channelId info:nil uid:0 joinSuccess:nil];
	if (code == 0) {
		[self setIdleTimerActive:NO];
	} else {
		dispatch_async(dispatch_get_main_queue(), ^{
			[self alertString:[NSString stringWithFormat:@"Join channel failed: %d", code]];
		});
	}
	
	if (self.isBroadcaster) {
		self.shouldEnhancer = YES;
	}
}

- (void)rtcEngine:(AgoraRtcEngineKit *)engine didJoinedOfUid:(NSUInteger)uid elapsed:(NSInteger)elapsed {
	VideoSession *userSession = [self videoSessionOfUid:uid];
	[self.rtcEngine setupRemoteVideo:userSession.canvas];
}

- (void)rtcEngine:(AgoraRtcEngineKit *)engine firstLocalVideoFrameWithSize:(CGSize)size elapsed:(NSInteger)elapsed {
	if (self.videoSessions.count) {
		[self updateInterfaceWithAnimation:NO];
	}
}

- (void)rtcEngine:(AgoraRtcEngineKit *)engine didOfflineOfUid:(NSUInteger)uid reason:(AgoraUserOfflineReason)reason {
	VideoSession *deleteSession;
	for (VideoSession *session in self.videoSessions) {
		if (session.uid == uid) {
			deleteSession = session;
		}
	}
	
	if (deleteSession) {
		[self.videoSessions removeObject:deleteSession];
		[deleteSession.hostingView removeFromSuperview];
		[self updateInterfaceWithAnimation:YES];
		
		if (deleteSession == self.fullSession) {
			self.fullSession = nil;
		}
	}
	[LZCTools HUDMessage:@"主播已离开直播间" delay:1];
	
	if(reason == AgoraUserOfflineReasonDropped){
		NSDictionary *param = @{
								@"user_id":_liveInfo.userid
								};
		[[NetworkTool sharedTool] requestWithName:@"删除直播" URLString:APICreateLives parameters:param method:@"DELETE" callBack:^(id responseObject) {
			
			NSDictionary *dict = responseObject[@"data"];
			NSLog(@"调用关闭直播间接口成功");
			
		}];
	}
}

//原Tencent IM方法
- (void)initTencentParam
{
    _videoPause   = NO;
    _videoFinished = YES;
    _isInVC       = NO;
    _log_switch   = NO;
    //_videoIsReady = videoIsReady;
    //_liveInfo     = info;
    if (_liveInfo.type == TCLiveListItemType_Live) {
        _isLivePlay = YES;
    }else{
        _isLivePlay = NO;
    }
    
    if (_liveInfo.type == TCLiveListItemType_Record) {
        _rtmpUrl      = _liveInfo.hls_play_url;
    } else {
        _rtmpUrl      = _liveInfo.playurl;
    }
    
    _biaoUrl = _liveInfo.biaoUrl;
    _gaoUrl = _liveInfo.gaoUrl;
    
    if ([_rtmpUrl hasPrefix:@"http:"]) {
        _rtmpUrl = [_rtmpUrl stringByReplacingOccurrencesOfString:@"http:" withString:@"https:"];
    }
    if ([_biaoUrl hasPrefix:@"http:"]) {
        _biaoUrl = [_biaoUrl stringByReplacingOccurrencesOfString:@"http:" withString:@"https:"];
    }
    if ([_gaoUrl hasPrefix:@"http:"]) {
        _gaoUrl = [_gaoUrl stringByReplacingOccurrencesOfString:@"http:" withString:@"https:"];
    }
    _rotate       = NO;
    _txLivePlayer =[[TXLivePlayer alloc] init];
    _txLivePlayer.enableHWAcceleration = YES;
    _msgHandler = [[AVIMMsgHandler alloc] init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackGround:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
	// 注册通知(礼物)
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showGift:)name:@"showGift" object:nil];
	
	_presentView = [[PresentView alloc] initWithFrame:CGRectMake(0, SH(4), 200, 200)];
	_presentView.centerY = self.view.centerY-100;
	[self.view addSubview:_presentView];
	_presentView.backgroundColor = kClearColor;
	_presentView.delegate = self;
	_presentView.hidden = YES;
	
	expensiveGiftCount = [[NSMutableArray alloc] init];
    //[self startPlay];
    _isNotifiedEnterGroup = NO;
    _isErrorAlert = NO;
    self.enableLinkMic = NO;
    
    _isResetVideoRecord = NO;
}

-(void) joinGroup {
    if ([[TIMManager sharedInstance] getLoginUser] == nil) {
        [[TCLoginModel sharedInstance] onForceOfflineAlert];
        return;
    }
    //    TCUserInfoData  *hostInfo = [[TCUserInfoModel sharedInstance] getUserProfile];
    NSDictionary *myUserInfo = GetUserDefaule(USERINFO);
    // 使用imsdk接口加群
    if (TCLiveListItemType_Live == _liveInfo.type)
    {
        [_msgHandler joinLiveRoom:_liveInfo.groupid handler:^(int errCode) {
            if (0 == errCode)
            {
                [_msgHandler sendEnterLiveRoomSenderInfo:_liveInfo.senderInfo];
            }
            else
            {
                if (!_isErrorAlert)
                {
                    _isErrorAlert = YES;
                    if (errCode == kError_GroupNotExist) {
                        [HUDHelper alertTitle:@"提示" message:kErrorMsgGroupNotExit cancel:@"确定" action:^{
                            [self closeVCWithRefresh:YES popViewController:YES];
                        }];
                    } else {
                        [HUDHelper alertTitle:@"提示" message:[NSString stringWithFormat:@"%@%d", kErrorMsgJoinGroupFailed, errCode] cancel:@"确定" action:^{
                            [self closeVCWithRefresh:YES popViewController:YES];
                        }];
                    }
                }
            }
        }];
    }
    
    //通知业务服务器有观众加群
    NSString* realGroupId = _liveInfo.groupid;
    //录播文件由于group已经解散，故使用fileid替代groupid
    if (TCLiveListItemType_Record == _liveInfo.type)
        realGroupId = _liveInfo.fileid;
    
    [[TCPlayerModel sharedInstance] enterGroup:myUserInfo[@"user_id"] type:_liveInfo.type liveUserId:_liveInfo.userid groupId:realGroupId nickName:myUserInfo[@"nickname"] headPic:myUserInfo[@"face"] handler:^(int errCode) {
        NSLog(@"========%d", errCode);
        //初始化群成员列表（会主动从业务服务器拉取一次群成员列表）
        [_logicView initAudienceList];
    }];
    
    _isNotifiedEnterGroup = YES;
}

- (void)closeVCWithRefresh:(BOOL)refresh popViewController: (BOOL)popViewController {
    //[self stopRtmp];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (_liveInfo) {
        
        if (_isNotifiedEnterGroup)
        {
            if (_msgHandler && TCLiveListItemType_Live == _liveInfo.type)
            {
                [_msgHandler sendQuitLiveRoomSenderInfo:_liveInfo.senderInfo];
                [_msgHandler releaseIMRef];
                [_msgHandler quitLiveRoom:_liveInfo.groupid handler:^(int errCode) {
                }];
            }
            
            //通知业务服务器观众退群
            //            TCUserInfoData  *hostInfo = [[TCUserInfoModel sharedInstance] getUserProfile];
            NSDictionary *userInfo = GetUserDefaule(USERINFO);
            NSString* realGroupId = _liveInfo.groupid;
            //录播文件由于group已经解散，故使用fileid替代groupid
            if (TCLiveListItemType_Record == _liveInfo.type)
                realGroupId = _liveInfo.fileid;
            
            [[TCPlayerModel sharedInstance] quitGroup:userInfo[@"user_id"] type:_liveInfo.type liveUserId:_liveInfo.userid groupId:realGroupId handler:^(int errCode) {
                
                
            }];
        }
    }
    if (refresh) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kTCLivePlayError" object:self];
        });
    }
    if (popViewController) {
        //调用声网的退出，所以暂时不用
        //[self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)clearLog {
    _logMsg = @"";
    [_logicView.statusView setText:@""];
    [_logicView.logViewEvt setText:@""];
}

//在这里初始化一个自定义的显示广告的View
- (void)initLogicView {
    if (_logicView) {
        return;
    }
    
    //逻辑View
    _logicView = [[TCPlayDecorateView alloc] initWithFrame:self.view.frame liveInfo:_liveInfo withLinkMic: self.enableLinkMic];
    _logicView.delegate = self;
    [_logicView setMsgHandler:_msgHandler];
    for (UIButton *button in self.sessionButtons) {
        [_logicView addSubview:button];
    }
    
    _videoRecordView = [[TCPlayUGCDecorateView alloc] initWithFrame:self.view.frame];
    _videoRecordView.delegate = self;
    _videoRecordView.hidden = YES;
    
    [self.view addSubview:_logicView];
    [self.view addSubview:_videoRecordView];
	
	//自定义广告(特殊礼物)View
	adInfoArr = [[NSMutableArray alloc] init];
	adInfoInQueueArr = [[NSMutableArray alloc] init];
	adView = [[UITableView alloc] initWithFrame:CGRectMake(0, SH(3)+80, 252, 110) style:UITableViewStylePlain];
	adView.backgroundColor = kWhiteColor;
	adView.hidden = YES;
	[_logicView addSubview:adView];
	[_logicView sendSubviewToBack:adView];
	adView.delegate = self;
	adView.dataSource  = self;
	[adView registerNib:[UINib nibWithNibName:@"ADViewCell" bundle:nil] forCellReuseIdentifier:@"adCell"];
	adView.delaysContentTouches = NO;
	for (id obj in adView.subviews) {
		if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]) {
			[obj setDelaysContentTouches:NO];
		}
	}
	[_logicView addSubview:_presentView];
}

//在低系统（如7.1.2）可能收不到这个回调，请在onAppDidEnterBackGround和onAppWillEnterForeground里面处理打断逻辑
- (void) onAudioSessionEvent: (NSNotification *) notification
{
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        if (_appIsInterrupt == NO) {
            if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
                if (!_videoPause) {
                    [_txLivePlayer pause];
                }
            }
            _appIsInterrupt = YES;
        }
    }else{
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            if (_appIsInterrupt == YES) {
                if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
                    if (!_videoPause) {
                        [_txLivePlayer resume];
                    }
                }
                _appIsInterrupt = NO;
            }
        }
    }
}

- (void)onAppDidEnterBackGround:(UIApplication*)app {
    if (_appIsInterrupt == NO) {
        if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
            if (!_videoPause) {
                [_txLivePlayer pause];
            }
        }
        _appIsInterrupt = YES;
    }
}

- (void)onAppWillEnterForeground:(UIApplication*)app {
    if (_appIsInterrupt == YES) {
        if (_playType == PLAY_TYPE_VOD_FLV || _playType == PLAY_TYPE_VOD_HLS || _playType == PLAY_TYPE_VOD_MP4) {
            if (!_videoPause) {
                [_txLivePlayer resume];
            }
        }
        _appIsInterrupt = NO;
    }
}

- (void)getMallInfo
{
    _mall = [[MallInLiveViewController alloc] init];
    _mall.uidForMall = self.liveInfo.userid;
    _mall.delegate = self;
    [self addChild:_mall inRect:_mall.view.frame];
    [self.logicView addSubview:_mall.view];
}

- (void)showGift:(NSNotification *)notification {
	
	NSDictionary *gift = notification.userInfo;
	NSLog(@"%@", gift);
	
	NSLog(@"--接收到展示礼物的消息通知--\n%@", gift);
	
	//    NSError *err;
	//    NSData *jsonData = [gift[@"msg"] dataUsingEncoding:NSUTF8StringEncoding];
	//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
	//                                                        options:NSJSONReadingMutableContainers
	//                                                          error:&err];
	
	NSDictionary *dic = gift[@"msg"];
	NSLog(@"%@", dic);
	
	
	static int count = 0;
	//    int continue = 0;
	NSString *giftType;
	//    if ([dic[@"type"] isEqual:@0]) {
	if ([[dic valueForKey:@"type"] isEqualToString:@"0"]) {
		giftType = [NSString stringWithFormat:@"%@_%d", dic[@"giftname"], count];
	}
	else if([[dic valueForKey:@"type"] isEqualToString:@"1"]){
		giftType = dic[@"giftname"];
	}
	else {
		[adInfoInQueueArr addObject:dic];
		NSLog(@"queue has %ld items", adInfoInQueueArr.count);
		if (adInfoArr.count == 0) {
			[adInfoArr addObject:dic];
			[adView reloadData];
			[self checkAdGift];
		}
		
		return;
	}
	
	count++;
	
	/*
	 GSPChatMessage *msg = [[GSPChatMessage alloc] init];
	 msg.text = [NSString stringWithFormat:@"赠送%@", dic[@"giftname"]];
	 msg.senderChatID = giftType;
	 msg.senderName = gift[@"nickName"];
	 
	 // 礼物模型
	 GiftModel *giftModel = [[GiftModel alloc] init];
	 giftModel.headImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:gift[@"headPic"]]]];
	 giftModel.name = msg.senderName;
	 giftModel.giftImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:dic[@"gifticon"]]]];
	 giftModel.giftName = dic[@"giftname"];
	 giftModel.giftCount = 1;
	 
	 AnimOperationManager *manager = [AnimOperationManager sharedManager];
	 manager.parentView = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController].view;
	 // 用用户唯一标识 msg.senderChatID 存礼物信息,model 传入礼物模型
	 [manager animWithUserID:[NSString stringWithFormat:@"%@-%@", gift[@"userId"], msg.senderChatID] model:giftModel finishedBlock:^(BOOL result) {
	 }];
	 */
	
	_presentView.hidden = NO;
	
	// 是否叠加的礼物
	PresentModel *giftModel = [PresentModel modelWithSender:gift[@"nickName"] giftName:dic[@"giftname"] icon:gift[@"headPic"] giftImageName:dic[@"gifticon"]];
	// 是否叠加的礼物
	if ([[NSString stringWithFormat:@"%@", dic[@"type"]] isEqualToString:@"0"]) {
		[_presentView insertPresentMessages:@[giftModel] showShakeAnimation:NO];
	}
	else
		[_presentView insertPresentMessages:@[giftModel] showShakeAnimation:YES];
	
	if (  [dic[@"id"] isEqualToString:@"22"] || [dic[@"id"] isEqualToString:@"21"] || [dic[@"id"] isEqualToString:@"9"] || [dic[@"id"] isEqualToString:@"19"]) {
		
		[self expensiveGift:gift];
	}
	
	
	// 写死 9 跑车 19 飞机 21 游轮 22 烟花
	//    if ([dic[@"id"] isEqualToString:@"9"]) {
	//        _car = [[redCar alloc]initWithIcons:gift[@"headPic"]  andName:gift[@"nickName"]];
	//        [self.view addSubview:_car];
	//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
	//            [_car removeFromSuperview];
	//        });
	//    }
	//    else if ([dic[@"id"] isEqualToString:@"19"]) {
	//        _plan = [[planView alloc]initWithicon:gift[@"headPic"] andName:gift[@"nickName"]];
	//        _plan.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/2);
	//        [self.view addSubview:_plan];
	//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
	//            [_plan removeFromSuperview];
	//        });
	//    }
	//    else if ([dic[@"id"] isEqualToString:@"21"]) {
	//        _ship = [[shipAction alloc] initWithName:gift[@"nickName"] and:gift[@"headPic"]];
	//        [self.view addSubview:_ship];
	//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
	//            [_ship removeFromSuperview];
	//        });
	//    }
	//    else if ([dic[@"id"] isEqualToString:@"22"]) {
	//        _flow = [[flowerAction alloc]init];
	//        [self.view addSubview:_flow];
	//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
	//            [_flow removeFromSuperview];
	//        });
	//    }
	
}


-(void)expensiveGift:(NSDictionary *)giftData{
	
	if (giftData == nil) {
	}
	else
	{
		[expensiveGiftCount addObject:giftData];
	}
	if(haohuaCount == 0){
		[self enGiftEspensive];
	}
}
-(void)enGiftEspensive{
	
	if (expensiveGiftCount.count == 0 || expensiveGiftCount == nil) {//判断队列中有item且不是满屏
		
		[expensiveGiftTime invalidate];
		
		expensiveGiftTime = nil;
		
		return;
		
	}
	
	NSDictionary *Dic = [expensiveGiftCount firstObject];
	
	[expensiveGiftCount removeObjectAtIndex:0];
	
	[self expensiveGiftPopView:Dic];
	
	
}
-(void)expensiveGiftPopView:(NSDictionary *)giftData{
	
	
	
	NSNumber *numbers = [giftData[@"msg"] valueForKey:@"id"];
	
	int number = [numbers intValue];
	
	if (number == 22) {
		haohuaCount = 1;
		_flow = [[flowerAction alloc]init];
		NSLog(@"***************************************烟花");
		
		[self.view addSubview:_flow];
		
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
			
			[_flow removeFromSuperview];
			haohuaCount = 0;
			if (expensiveGiftCount.count >0) {
				
				[self expensiveGift:nil];
				
			}
			
		});
	}
	else if (number == 21){
		haohuaCount = 1;
		
		NSLog(@"***************************************邮轮");
		_ship = [[shipAction alloc]initWithName:[giftData valueForKey:@"nickName"] and:[giftData valueForKey:@"headPic"]];
		[self.view addSubview:_ship];
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
			[_ship removeFromSuperview];
			haohuaCount = 0;
			if (expensiveGiftCount.count >0) {
				
				[self expensiveGift:nil];
				
			}
			
			
		});
		
	}
	else if (number == 9){
		haohuaCount = 1;
		
		_car = [[redCar alloc]initWithIcons:[giftData valueForKey:@"headPic"] andName:[giftData valueForKey:@"nickName"]];
		[self.view addSubview:_car];
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
			[_car removeFromSuperview];
			haohuaCount = 0;
			if (expensiveGiftCount.count >0) {
				[self expensiveGift:nil];
				
			}
			
			
		});
	}
	else if (number == 19) {
		haohuaCount = 1;
		
		_plan = [[planView alloc]initWithicon:[giftData valueForKey:@"headPic"] andName:[giftData valueForKey:@"nickName"]];
		_plan.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/2);
		[self.view addSubview:_plan];
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
			[_plan removeFromSuperview];
			haohuaCount = 0;
			
			if (expensiveGiftCount.count >0) {
				[self expensiveGift:nil];
				
			}
			
		});
	}
	
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	return 110;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	ADViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"adCell"];
	NSDictionary *info = adInfoArr[indexPath.row];
	cell.info = info;
	cell.delegate = self;
	currentCell = cell;
	return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	NSLog(@"I was selected");
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	NSLog(@"the cell num in here is %ld", adInfoArr.count);
	if (adInfoArr.count > 0) {
		adView.alpha = 1.0;
		adView.hidden = NO;
	}else {
		adView.hidden = YES;
	}
	return adInfoArr.count;
}

- (void)jumpToLink:(NSString *)url
{
	WKWebViewController *vc = [[WKWebViewController alloc] init];
	NSString *urlStr;
	if ([url containsString:@"http"]) {
		urlStr = url;
	}
	else {
		urlStr = [NSString stringWithFormat:@"http://%@",url];
	}
	[vc loadWebURLSring:urlStr];
	[self.navigationController pushViewController:vc animated:YES];
	NSLog(@"jump has been clicked");
}

#pragma mark - PresentViewDelegate

- (PresentViewCell *)presentView:(PresentView *)presentView cellOfRow:(NSInteger)row
{
	return [[CustonCell alloc] initWithRow:row];
}

- (void)presentView:(PresentView *)presentView configCell:(PresentViewCell *)cell model:(id<PresentModelAble>)model
{
	CustonCell *customCell = (CustonCell *)cell;
	customCell.model = model;
}

- (void)presentView:(PresentView *)presentView didSelectedCellOfRowAtIndex:(NSUInteger)index
{
	CustonCell *cell = [presentView cellForRowAtIndex:index];
	NSLog(@"你点击了：%@", cell.model.giftName);
}

- (void)presentView:(PresentView *)presentView animationCompleted:(NSInteger)shakeNumber model:(id<PresentModelAble>)model
{
	NSLog(@"%@礼物的连送动画执行完成", model.giftName);
}

/**观众端分享按钮*/
- (void)clickDownShare:(UIButton *)button {
	
	
	AlertShareView *alert = [[AlertShareView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
	
	
	TCLiveUserInfo *user = _liveInfo.userinfo;
	
	NSString *url = [NSString stringWithFormat:@"%@/mobile/download/a/hostUserId/%@", APIBackEndUrl, GetUserDefaule(CURRLIVE)[@"hostId"]];
	
	NSString *text = [NSString stringWithFormat:@"%@正在直播……", user.nickname];
	
	NSString *img = user.headpic;
	
	NSString *title = [NSString stringWithFormat:@"%@ %@", [GetUserDefaule(CURRLIVE) valueForKey:@"title"], [GetUserDefaule(CURRLIVE) valueForKey:@"intro"]];
	
	NSDictionary *p = @{@"url":url,
						@"title":title,
						@"text":text,
						@"img":img};
	
	NSLog(@"分享参数 %@", p);
	
	[alert initShow:p];
	
	//    [self.view addSubview:alert];
	
	UIWindow *window = [[UIApplication sharedApplication].delegate window];
	[window addSubview:alert];
	
}
//循环线程检测有无自定义广告礼物
- (void)checkAdGift {
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
		
		if(adInfoArr.count > 0) {
			[adInfoArr removeObjectAtIndex:0];
			[adInfoInQueueArr removeObjectAtIndex:0];
			[UIView animateKeyframesWithDuration:1.0 delay:0.0 options:UIViewKeyframeAnimationOptionAllowUserInteraction animations:^{
				adView.alpha = 0.05;
			} completion:^(BOOL finished) {
				if (finished) {
					if (adInfoInQueueArr.count > 0) {
						[adInfoArr addObject:adInfoInQueueArr[0]];
						[adView reloadData];
						[self checkAdGift];
					}
					[adView reloadData];
				}
			}];
		}
	});
}

@end
